import fetch from 'dva/fetch';
import { notification } from 'antd';
import router from 'umi/router';
import hash from 'hash.js';
import * as qs from 'qs';
import { fakeDataApi, isAntdPro } from './utils';
import uiUtils from './uiUtils';

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

/**
 * 获取公共的url
 */
export function getWebPath(url) {
  // let commomUrl = 'https://www.new8090.net/mall/'; //公司内部测试
  // let commomUrl = 'https://shop.dfww.com.cn/mall/';//客户正式
  let commomUrl = 'http://localhost:8988/mall/';
  commomUrl = `${commomUrl}${typeof url === 'undefined' ? '' : url}`.replace('/mall//', '/mall/');
  return commomUrl;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [option] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, option) {
  /* eslint-disable no-param-reassign */
  if (url.indexOf(getWebPath('')) === -1) {
    url = fakeDataApi() + url;
  }

  const checkStatus = response => {
    if (response.status >= 200 && response.status < 300) {
      return response;
    }
    const errortext = codeMessage[response.status] || response.statusText;
    notification.error({
      message: `请求错误 ${response.status}: ${response.url}`,
      description: errortext,
    });
    const error = new Error(errortext);
    error.name = response.status;
    error.response = response;
    throw error;
  };

  const cachedSave = (response, hashcode) => {
    /**
     * Clone a response data and store it in sessionStorage
     * Does not support data other than json, Cache only json
     */
    const contentType = response.headers.get('Content-Type');
    if (contentType && contentType.match(/application\/json/i)) {
      // All data is saved as text
      response
        .clone()
        .text()
        .then(content => {
          if (url.indexOf('mall/infarea/list') < 0) {
            sessionStorage.setItem(hashcode, content);
            sessionStorage.setItem(`${hashcode}:timestamp`, Date.now());
          }
        });
    }
    return response;
  };

  /**
   * 处理数据异常情况，段大志修改
   * 如：session过期，自动跳转到登录页面
   * @returns {*}
   */
  const handleError = response => {
    response
      .clone()
      .text()
      .then(res => {
        if (res) {
          let json;
          try {
            json = JSON.parse(res);
          } catch (e) {
            json = null;
          }
          if (json) {
            if (json.code !== null && json.code !== undefined) {
              if (json.code === 102) {
                // @HACK
                /* eslint-disable no-underscore-dangle */
                window.g_app._store.dispatch({
                  type: 'login/logout',
                });
              } else if (json.code !== 0) {
                if (url.indexOf('/sys/login') < 0) {
                  uiUtils.showAlert(json.msg, 'error');
                }
              }
            }
          }
        }
      });
    return response;
  };

  const options = {
    expirys: isAntdPro(),
    ...option,
  };
  /**
   * Produce fingerprints based on url and parameters
   * Maybe url has the same parameters
   */
  const fingerprint = url + (options.body ? JSON.stringify(options.body) : '');
  const hashcode = hash
    .sha256()
    .update(fingerprint)
    .digest('hex');

  const defaultOptions = {
    credentials: 'include',
    // 表示是否跨域，都会发送凭证信息包含 cookie和安全校验如basic auth;
    // 详细说明：https://developer.mozilla.org/zh-CN/docs/Web/API/Request/credentials
  };
  const newOptions = { ...defaultOptions, ...options };
  if (
    newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE'
  ) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
      };

      let requestContentType = newOptions.contentType;
      if (!requestContentType) {
        requestContentType = newOptions.ContentType;
      }
      if (!requestContentType) {
        requestContentType = newOptions['Content-Type'];
      }

      if (!requestContentType) {
        // 等价 (requestContentType != null && requestContentType !== '' && requestContentType !== undefined)
        newOptions.headers = {
          // 在这里设置默认的 content-type
          'Content-Type': 'application/json; charset=utf-8', // 后台使用 @ResponseBody的Bean进行接收
          // 'Content-Type': 'application/x-www-form-urlencoded', // 后台使用 @RequestParam 进行单个接收
          ...newOptions.headers,
        };
      } else {
        newOptions.headers = {
          'Content-Type': requestContentType,
          ...newOptions.headers,
        };
      }

      requestContentType = newOptions.headers['Content-Type'];
      if (requestContentType.match(/application\/json/i)) {
        newOptions.body = JSON.stringify(newOptions.body);
      } else {
        // requestContentType.includes('application/x-www-form-urlencoded')
        newOptions.body = qs.stringify(newOptions.body, { encodeValuesOnly: true });
      }
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
      };
    }
  }

  const expirys = options.expirys && 60;
  // options.expirys !== false, return the cache,
  if (options.expirys !== false) {
    const cached = sessionStorage.getItem(hashcode);
    const whenCached = sessionStorage.getItem(`${hashcode}:timestamp`);
    if (cached !== null && whenCached !== null) {
      const age = (Date.now() - whenCached) / 1000;
      if (age < expirys) {
        const response = new Response(new Blob([cached]));
        return response.json();
      }
      sessionStorage.removeItem(hashcode);
      sessionStorage.removeItem(`${hashcode}:timestamp`);
    }
  }

  //return fetch(url, newOptions)
  return fetch(`${url}`, newOptions)
    .then(checkStatus)
    .then(response => cachedSave(response, hashcode))
    .then(response => handleError(response))
    .then(response => {
      // DELETE and 204 do not return data by default
      // using .json will report an error.
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      return response.json();
    })
    .catch(e => {
      const status = e.name;
      if (status === 401) {
        // @HACK
        /* eslint-disable no-underscore-dangle */
        window.g_app._store.dispatch({
          type: 'login/logout',
        });
        return;
      }
      // environment should not be used
      if (status === 403) {
        router.push('/exception/403');
        return;
      }
      if (status <= 504 && status >= 500) {
        router.push('/exception/500');
        return;
      }
      if (status >= 404 && status < 422) {
        router.push('/exception/404');
      }
    });
}

/**
 * 段大志
 * 把 reqeust对象封装成Promise的对象
 * @returns {Promise<Object>}
 */
export async function requestPromise(url, option) {
  return request(url, option);
}

/**
 * 远程校验简单封装
 * @returns {Promise<void>}
 */
export function reqeustRemoteValidate(url, option) {
  const options = {
    contentType: 'application/x-www-form-urlencoded',
    ...option,
  };

  return new Promise((resolve, reject) => {
    requestPromise(url, options)
      .then(res => {
        if (res && res.ok) {
          resolve(res.ok);
        } else {
          reject(new Error(res && res.error ? res.error : '远程校验有误!'));
        }
      })
      .catch(() => reject(new Error('远程校验失败!')));
  });
}

/**
 * 请求带有分页的列表数据的封装简化操作
 */
export function requestLists(_this, url, params) {
  _this.setState({ loading: true });
  requestPromise(url, {
    method: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    body: params,
    _this,
  }).then(res => {
    _this.setState({ loading: false });
    if (res) {
      if (res && res.code === 0) {
        if (res && res.page) {
          const list = res.page.list.map((item, index) => {
            item.key = index;
            return item;
          });
          _this.setState({
            list,
            selectedIndexs: [],
            selectedRows: [],
            selectedIds: [],
            pagination: uiUtils.pagination(res, (current, limit) => {
              _this.params.page = current;
              if (typeof limit !== 'undefined') {
                _this.params.limit = limit;
              }
              _this.requestList();
            }),
          });
          //如果当前页，没有数据，我们往前查询一页
          if (res.page.currPage > res.page.totalPage && res.page.totalPage > 0) {
            _this.params.page = res.page.totalPage;
            _this.requestList();
          }
        }
      }
    }
  });
}
